// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Linq;

namespace SnapObjects.Data
{
    internal class JsonTemplateImportSchemaParser : ITemplateImportSchemaParser
    {
        private ITemplateImportProvider _provider;

        private readonly TemplateImportSchema _schema;

        public JsonTemplateImportSchemaParser()
        {
            _schema = new TemplateImportSchema();
        }

        public TemplateImportSchema Parse(string template, ITemplateImportProvider provider)
        {
            _provider = provider;

            var _reader = JNodeReader.Parse(template);

            this.Parse(_reader);

            if (_schema.Nodes.Count == 0)
            {
                throw new Exception(Properties.Resource.TEMPLATEIMPORT_TYPENOTMATCH_EXCEPTION);
            }

            return _schema;
        }

        private void Parse(INodeReader reader)
        {
            while (reader.Read())
            {
                if (reader.CurrentNodeType == DataNodeType.Value)
                {
                    var item = reader.ValueReader;

                    if (!_schema.Nodes.ContainsKey(item.Name))
                    {
                        var column = _provider.GetColumns().FirstOrDefault
                        (
                            x => x.Key.Equals(item.Name, StringComparison.OrdinalIgnoreCase)
                        );

                        if (column.Key != null)
                        {
                            var node = new TemplateImportShcemaNode(column.Key, column.Value);

                            _schema.Nodes.Add(item.Name, node);
                        }
                    }
                }
                else
                {
                    var r = reader.ReadAsNode();

                    this.Parse(r);
                }
            }
        }
    }
}
